//
//  YGJQuickLoginVC.m
//  ygj-customer-iOS
//
//  Created by apple on 17/3/2.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YGJQuickLoginVC.h"
#import "SVProgressHUD.h"
#import "HXNetwork.h"
#import "YGJUserProcotolVC.h"
#import "UIColor+Hex.h"

@interface YGJQuickLoginVC ()

@property (nonatomic,strong) HXResponseManager *manager;

@end

@implementation YGJQuickLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"快速登录";
    
    //设置倒计时总时长
    _secondsCountDown = 60;//60秒倒计时
    
    _manager = [HXResponseManager manager];
    
    [self setButtonStyle];

    
}

-(void) setButtonStyle {
    
    _verification_btn.backgroundColor = [UIColor colorWithHexString:@"#9CD3FF"];
    _verification_btn.layer.cornerRadius = 5;
    _login_btn.backgroundColor = [UIColor colorWithHexString:@"#9CD3FF"];
    _login_btn.layer.cornerRadius = 5;
}

-(void)timeFireMethod{
    //倒计时-1
    _secondsCountDown--;
    //修改倒计时标签现实内容
    [_verification_btn setTitle:[NSString stringWithFormat:@"%d秒",_secondsCountDown] forState:UIControlStateNormal];
    _verification_btn.userInteractionEnabled=NO;
    _verification_btn.backgroundColor = [UIColor colorWithHexString:@"#9CD3FF"];

    //当倒计时到0时，做需要的操作，比如验证码过期不能提交
    if(_secondsCountDown==0){
        [_countDownTimer invalidate];
        [_verification_btn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _verification_btn.backgroundColor = [UIColor colorWithHexString:@"#1D90FF"];
        _verification_btn.userInteractionEnabled=YES;
        
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(BOOL) textFieldShouldEndEditing:(UITextField *)textField {
    if (textField.tag == 101) {
//        NSLog(@"结束手机号码是-->%@",textField.text);
        _phone_number = textField.text;
    }
    if (textField.tag == 102) {
        _verification_code = textField.text;
    }
    return YES;
}
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    

    
    if (textField.tag == 101) {
        _phone_number = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (_phone_number.length < 11 || _phone_number.length >11) {
            _verification_btn.userInteractionEnabled=NO;
            _verification_btn.backgroundColor = [UIColor colorWithHexString:@"#9CD3FF"];
        }else{
            _verification_btn.userInteractionEnabled=YES;
            _verification_btn.backgroundColor = [UIColor colorWithHexString:@"#1D90FF"];
        }
    }
    if (textField.tag == 102) {
        _verification_code = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (_verification_code.length < 6 || _verification_code.length>6) {
            _login_btn.userInteractionEnabled=NO;
            _login_btn.backgroundColor = [UIColor colorWithHexString:@"#9CD3FF"];
        }else{
            _login_btn.userInteractionEnabled=YES;
            _login_btn.backgroundColor = [UIColor colorWithHexString:@"#1D90FF"];
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];    //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
    return YES;
}

#pragma mark 控件点击事件处理
- (IBAction)GetVerificationCode:(UIButton *)sender {
    
   
    //开始倒计时
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
    
    
    NSDictionary * params = @{@"phone":_phone_number};
    
    [SVProgressHUD show];
    [_manager getWithUrl:@"customer/verify/sms" params:params success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSString * statusCode = [responseObject objectForKey:@"status"];
        NSString * statusSubCode = [[responseObject objectForKey:@"body"] objectForKey:@"status"] ;
        
        if ([statusCode integerValue] == 0 && [statusSubCode integerValue] == 0)
        {
            [SVProgressHUD showInfoWithStatus:@"验证码已发送"];
        }else{
            [SVProgressHUD showInfoWithStatus:[[responseObject objectForKey:@"body"] objectForKey:@"reason"]];
        }
        [SVProgressHUD dismiss];
    } fail:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [SVProgressHUD showErrorWithStatus:(NSString *)error];
    }];

}

- (IBAction)Login:(id)sender {

    if (_phone_number != nil && _verification_code != nil) {
        NSDictionary * params = @{@"username":_phone_number,@"phoneValid":_verification_code,@"zip":@"+86"};
        
        [SVProgressHUD show];
        [_manager configRequestSerializerMethod:HXRequestSerializerMethodJSON];

        [_manager postWithUrl:@"customer/quick-login" params:params success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
            
            NSString * statusCode = [responseObject objectForKey:@"status"];
            NSString * statusSubCode = [[responseObject objectForKey:@"body"] objectForKey:@"status"] ;
            NSString * token = [[responseObject objectForKey:@"body"] objectForKey:@"accessToken"];
            NSString * vip = [[responseObject objectForKey:@"body"] objectForKey:@"vip"];
            
            if ([statusCode integerValue] == 0 && [statusSubCode integerValue] == 0) {
                
                [self userdafalutWithString:token WithVip:vip];
            }else{
                [[NSUserDefaults standardUserDefaults] setObject:@"notLogin" forKey:@"login"];
                [SVProgressHUD showInfoWithStatus:[[responseObject objectForKey:@"body"] objectForKey:@"reason"]];
            }
            
            [SVProgressHUD dismiss];
        } fail:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            [SVProgressHUD showErrorWithStatus:(NSString *)error];
        }];

    }
    
    
}

#pragma mark 存储token 和 登录状态
-(void) userdafalutWithString:(NSString *) token WithVip:(NSString *)vip {
    
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] setObject:vip forKey:@"vip"];
    [[NSUserDefaults standardUserDefaults] setObject:@"login" forKey:@"login"];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)UserProcotol:(id)sender {
    
    YGJUserProcotolVC * userproVC = [[YGJUserProcotolVC alloc] initWithNibName:@"YGJUserProcotolVC" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:userproVC animated:YES];
    
}

- (IBAction)PhoneNumberTextField:(id)sender {
    
}

- (IBAction)VerificationCodeTextField:(id)sender {
    
}

- (IBAction)NoGetterVerificationCode:(id)sender {
   
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请检查手机号码是否正确,如正确,但长时间未收到短信,请拨打免费客服电话获取验证码。" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction * okaction = [UIAlertAction actionWithTitle:@"致电客服" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[NSMutableString alloc] initWithFormat:@"telprompt://%@",@"4000022699"]] options:@{} completionHandler:nil];
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
    
    }];
    
    [alertController addAction:okaction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}




@end
